<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/23/023
 * Time: 10:15
 */

namespace app\api\service;

use app\lib\exception\AdminException;
use app\lib\exception\TokenException;


class AdminToken extends Token {

    /**
     * 获取管理员token
     * @param array $admin
     * @return string
     * @throws AdminException
     */
    public function get($admin = []) {
        if(!$admin){
            throw new AdminException();
        }
        return $this->grantToken($admin);
    }

    /**
     * 创建管理员token
     * @param $admin
     * @return string
     */
    private function grantToken($admin){
        $cachedValue = $this->prepareCachedValue($admin);
        $token = $this->saveToCache($cachedValue);
        return $token;
    }

    /**
     * 将管理员token存入缓存
     * @param $cachedValue
     * @return string
     * @throws TokenException
     */
    private function saveToCache($cachedValue){
        $key = self::generateToken();
        $value = json_encode($cachedValue);
        $expire_in = config('setting.admin_token_expire_in');

        $request = cache($key, $value, $expire_in);
        if(!$request){
            throw new TokenException([
                'msg' => '服务器缓存异常',
                'errorCode' => 40001
            ]);
        }
        return $key;
    }

    /**
     * 获取token值
     * @param $admin
     * @return mixed
     */
    private function prepareCachedValue($admin){
        $cachedValue['admin_username'] = $admin->username;
        $cachedValue['admin_id'] = $admin->id;
        // scope=16 代表App用户的权限数值
        $cachedValue['scope'] = $admin->scope;
        $cachedValue['type'] = 'admin';

        return $cachedValue;
    }

}